using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using JGSY.CMS.LowCode.Platform.Infrastructure.Configuration;
using JGSY.CMS.LowCode.Platform.Infrastructure.Configuration.Models;
using JGSY.CMS.LowCode.Platform.Infrastructure.Configuration.Extensions;
using JGSY.CMS.LowCode.Platform.Infrastructure.Services.Notification;

namespace JGSY.CMS.LowCode.Platform.Controllers;

/// <summary>
/// 基础设施层配置映射控制器 - 增强版
/// </summary>
[ApiController]
[Route("api/infrastructure/configuration")]
public class InfrastructureConfigurationController : ControllerBase
{
    private readonly ConfigurationMappingFactory _configFactory;
    private readonly EnhancedConfigurationMappingFactory _enhancedConfigFactory;
    private readonly IOptionsMonitor<DatabaseConfiguration> _databaseConfig;
    private readonly IOptionsMonitor<JwtConfiguration> _jwtConfig;
    private readonly IOptionsMonitor<ServerConfiguration> _serverConfig;
    private readonly IOptionsMonitor<CacheSettingsConfiguration> _cacheConfig;
    private readonly ILogger<InfrastructureConfigurationController> _logger;

    public InfrastructureConfigurationController(
        ConfigurationMappingFactory configFactory,
        EnhancedConfigurationMappingFactory enhancedConfigFactory,
        IOptionsMonitor<DatabaseConfiguration> databaseConfig,
        IOptionsMonitor<JwtConfiguration> jwtConfig,
        IOptionsMonitor<ServerConfiguration> serverConfig,
        IOptionsMonitor<CacheSettingsConfiguration> cacheConfig,
        ILogger<InfrastructureConfigurationController> logger)
    {
        _configFactory = configFactory;
        _enhancedConfigFactory = enhancedConfigFactory;
        _databaseConfig = databaseConfig;
        _jwtConfig = jwtConfig;
        _serverConfig = serverConfig;
        _cacheConfig = cacheConfig;
        _logger = logger;
    }

    /// <summary>
    /// 获取数据库配置映射
    /// </summary>
    /// <returns>数据库配置</returns>
    [HttpGet("database")]
    public ActionResult<object> GetDatabaseConfiguration()
    {
        try
        {
            var config = _configFactory.GetDatabaseConfiguration();
            
            // 隐藏敏感信息
            return Ok(new
            {
                databaseType = config.DatabaseType,
                connectionTimeout = config.Database.ConnectionTimeout,
                commandTimeout = config.Database.CommandTimeout,
                maxRetryCount = config.Database.MaxRetryCount,
                enableDetailedErrors = config.Database.EnableDetailedErrors,
                connectionStrings = new
                {
                    hasConnectionString = !string.IsNullOrEmpty(config.ConnectionStrings.GetConnectionString(config.DatabaseType))
                }
            });
        }
        catch (Exception ex)
        {
            return BadRequest(new { error = ex.Message });
        }
    }

    /// <summary>
    /// 获取服务器配置映射
    /// </summary>
    /// <returns>服务器配置</returns>
    [HttpGet("server")]
    public ActionResult<object> GetServerConfiguration()
    {
        try
        {
            var config = _configFactory.GetServerConfiguration();
            
            return Ok(new
            {
                port = config.Port,
                environment = config.Environment,
                host = config.Host,
                useHttps = config.UseHttps,
                httpsPort = config.HttpsPort,
                hasCertificate = !string.IsNullOrEmpty(config.CertificatePath)
            });
        }
        catch (Exception ex)
        {
            return BadRequest(new { error = ex.Message });
        }
    }

    /// <summary>
    /// 获取JWT配置映射（隐藏敏感信息）
    /// </summary>
    /// <returns>JWT配置</returns>
    [HttpGet("jwt")]
    public ActionResult<object> GetJwtConfiguration()
    {
        try
        {
            var config = _configFactory.GetJwtConfiguration();
            
            return Ok(new
            {
                issuer = config.Issuer,
                audience = config.Audience,
                expiryMinutes = config.ExpiryMinutes,
                refreshExpiryDays = config.RefreshExpiryDays,
                validateIssuer = config.ValidateIssuer,
                validateAudience = config.ValidateAudience,
                validateLifetime = config.ValidateLifetime,
                validateIssuerSigningKey = config.ValidateIssuerSigningKey,
                hasSecret = !string.IsNullOrEmpty(config.Secret)
            });
        }
        catch (Exception ex)
        {
            return BadRequest(new { error = ex.Message });
        }
    }

    /// <summary>
    /// 获取日志配置映射
    /// </summary>
    /// <returns>日志配置</returns>
    [HttpGet("logging")]
    public ActionResult<LoggingConfiguration> GetLoggingConfiguration()
    {
        try
        {
            var config = _configFactory.GetLoggingConfiguration();
            return Ok(config);
        }
        catch (Exception ex)
        {
            return BadRequest(new { error = ex.Message });
        }
    }

    /// <summary>
    /// 获取缓存配置映射概要
    /// </summary>
    /// <returns>缓存配置概要</returns>
    [HttpGet("cache")]
    public ActionResult<object> GetCacheConfiguration()
    {
        try
        {
            var config = _configFactory.GetCacheSettingsConfiguration();
            
            return Ok(new
            {
                provider = config.Provider,
                redis = new
                {
                    hasConnectionString = !string.IsNullOrEmpty(config.Redis.ConnectionString),
                    defaultExpiration = config.Redis.DefaultExpiration,
                    database = config.Redis.Database,
                    maxRetries = config.Redis.MaxRetries,
                    connectionTimeout = config.Redis.ConnectionTimeout,
                    commandTimeout = config.Redis.CommandTimeout
                },
                cache = new
                {
                    type = config.Cache.Type,
                    testEnabled = config.Cache.TestEnabled,
                    testTTL = config.Cache.TestTTL,
                    testKeyPrefix = config.Cache.TestKeyPrefix
                }
            });
        }
        catch (Exception ex)
        {
            return BadRequest(new { error = ex.Message });
        }
    }

    /// <summary>
    /// 获取完整配置概要
    /// </summary>
    /// <returns>配置概要</returns>
    [HttpGet("summary")]
    public ActionResult<ConfigurationSummary> GetConfigurationSummary()
    {
        try
        {
            var summary = HttpContext.RequestServices.GetConfigurationSummary();
            return Ok(summary);
        }
        catch (Exception ex)
        {
            return BadRequest(new { error = ex.Message });
        }
    }

    /// <summary>
    /// 验证所有配置
    /// </summary>
    /// <returns>验证结果</returns>
    [HttpGet("validate")]
    public ActionResult<ConfigurationValidationResult> ValidateConfigurations()
    {
        try
        {
            var validationResult = HttpContext.RequestServices.ValidateConfigurations();
            
            if (validationResult.IsValid)
            {
                return Ok(validationResult);
            }
            else
            {
                return BadRequest(validationResult);
            }
        }
        catch (Exception ex)
        {
            return BadRequest(new ConfigurationValidationResult
            {
                IsValid = false,
                Errors = { $"Validation failed: {ex.Message}" }
            });
        }
    }

    /// <summary>
    /// 清除配置缓存
    /// </summary>
    /// <returns>操作结果</returns>
    [HttpPost("cache/clear")]
    public ActionResult ClearConfigurationCache()
    {
        try
        {
            _configFactory.ClearCache();
            return Ok(new { message = "Configuration cache cleared successfully" });
        }
        catch (Exception ex)
        {
            return BadRequest(new { error = ex.Message });
        }
    }

    /// <summary>
    /// 获取配置健康状态
    /// </summary>
    /// <returns>健康状态</returns>
    [HttpGet("health")]
    public ActionResult<object> GetConfigurationHealth()
    {
        try
        {
            var validationResult = HttpContext.RequestServices.ValidateConfigurations();
            var summary = HttpContext.RequestServices.GetConfigurationSummary();
            
            return Ok(new
            {
                isHealthy = validationResult.IsValid,
                lastCheck = DateTime.UtcNow,
                summary = summary,
                errors = validationResult.Errors,
                warnings = validationResult.Warnings
            });
        }
        catch (Exception ex)
        {
            return Ok(new
            {
                isHealthy = false,
                lastCheck = DateTime.UtcNow,
                error = ex.Message
            });
        }
    }

    #region 增强版 API 端点

    /// <summary>
    /// 获取完整的应用配置映射（增强版）
    /// </summary>
    /// <returns>完整的配置对象</returns>
    [HttpGet("enhanced/complete")]
    public ActionResult<object> GetEnhancedCompleteConfiguration()
    {
        try
        {
            _logger.LogInformation("Getting enhanced complete configuration");
            var config = _enhancedConfigFactory.GetCompleteApplicationSettings();
            
            return Ok(new
            {
                version = config.Version,
                environment = config.Environment,
                loadedAt = config.LoadedAt,
                database = new
                {
                    type = config.Database.DatabaseType,
                    hasConnectionStrings = config.Database.ConnectionStrings != null
                },
                jwt = new
                {
                    issuer = config.Jwt.Issuer,
                    audience = config.Jwt.Audience,
                    expiryMinutes = config.Jwt.ExpiryMinutes,
                    hasSecret = !string.IsNullOrEmpty(config.Jwt.Secret)
                },
                server = new
                {
                    port = config.Server.Port,
                    environment = config.Server.Environment
                },
                cache = new
                {
                    provider = config.CacheSettings.Provider,
                    hasRedis = config.CacheSettings.Redis != null
                },
                security = new
                {
                    enableMFA = config.Security.EnableMFA,
                    enableThreatDetection = config.Security.EnableThreatDetection,
                    maxLoginAttempts = config.Security.MaxLoginAttempts
                },
                features = new
                {
                    upload = new
                    {
                        storageType = config.Upload.StorageType,
                        maxFileSize = config.Upload.MaxFileSize
                    },
                    cors = new
                    {
                        origin = config.Cors.Origin
                    },
                    api = new
                    {
                        prefix = config.Api.Prefix,
                        version = config.Api.Version
                    },
                    extensions = new
                    {
                        databaseExtensions = config.Extension.EnableDatabaseExtensions,
                        autoLoad = config.Extension.AutoLoad
                    }
                }
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get enhanced complete configuration");
            return BadRequest(new { error = ex.Message });
        }
    }

    /// <summary>
    /// 获取配置健康报告（增强版）
    /// </summary>
    /// <returns>配置健康状态</returns>
    [HttpGet("enhanced/health")]
    public ActionResult<ConfigurationHealthReport> GetEnhancedHealthReport()
    {
        try
        {
            _logger.LogInformation("Getting enhanced configuration health report");
            var healthReport = _enhancedConfigFactory.GetHealthReport();
            
            return Ok(healthReport);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get enhanced health report");
            return BadRequest(new ConfigurationHealthReport
            {
                IsHealthy = false,
                CheckedAt = DateTime.UtcNow,
                Issues = { $"Health check failed: {ex.Message}" }
            });
        }
    }

    /// <summary>
    /// 获取配置元数据（增强版）
    /// </summary>
    /// <returns>配置元数据</returns>
    [HttpGet("enhanced/metadata")]
    public ActionResult<ConfigurationMetadata> GetConfigurationMetadata()
    {
        try
        {
            _logger.LogInformation("Getting configuration metadata");
            var metadata = _enhancedConfigFactory.GetConfigurationMetadata();
            
            return Ok(metadata);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get configuration metadata");
            return BadRequest(new { error = ex.Message });
        }
    }

    /// <summary>
    /// 导出配置为JSON（增强版）
    /// </summary>
    /// <param name="includeSensitive">是否包含敏感信息（默认：false）</param>
    /// <returns>JSON格式的配置</returns>
    [HttpGet("enhanced/export")]
    public ActionResult<string> ExportConfigurationAsJson([FromQuery] bool includeSensitive = false)
    {
        try
        {
            _logger.LogInformation("Exporting configuration as JSON, includeSensitive: {IncludeSensitive}", includeSensitive);
            
            if (includeSensitive)
            {
                _logger.LogWarning("Exporting configuration with sensitive data included");
            }
            
            var json = _enhancedConfigFactory.ExportConfigurationAsJson(includeSensitive);
            
            return Ok(new
            {
                exportedAt = DateTime.UtcNow,
                includeSensitive = includeSensitive,
                data = json
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to export configuration as JSON");
            return BadRequest(new { error = ex.Message });
        }
    }

    /// <summary>
    /// 验证所有配置（增强版）
    /// </summary>
    /// <returns>验证结果</returns>
    [HttpGet("enhanced/validate")]
    public ActionResult<EnhancedConfigurationValidationResult> ValidateAllConfigurations()
    {
        try
        {
            _logger.LogInformation("Validating all configurations");
            var validationResult = _enhancedConfigFactory.ValidateAllConfigurations();
            
            if (validationResult.IsValid)
            {
                return Ok(validationResult);
            }
            else
            {
                _logger.LogWarning("Configuration validation failed with {ErrorCount} errors", 
                    validationResult.Errors.Count);
                return BadRequest(validationResult);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Configuration validation failed with exception");
            return BadRequest(new EnhancedConfigurationValidationResult
            {
                IsValid = false,
                Errors = { $"Validation failed: {ex.Message}" },
                ValidatedAt = DateTime.UtcNow
            });
        }
    }

    /// <summary>
    /// 清除配置缓存（增强版）
    /// </summary>
    /// <returns>操作结果</returns>
    [HttpPost("enhanced/clear-cache")]
    public ActionResult ClearEnhancedConfigurationCache()
    {
        try
        {
            _logger.LogInformation("Clearing enhanced configuration cache");
            _enhancedConfigFactory.ClearCache();
            _configFactory.ClearCache();
            
            return Ok(new
            {
                message = "Configuration cache cleared successfully",
                clearedAt = DateTime.UtcNow
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to clear enhanced configuration cache");
            return BadRequest(new { error = ex.Message });
        }
    }

    /// <summary>
    /// 获取特定配置节的映射（增强版）
    /// </summary>
    /// <param name="section">配置节名称</param>
    /// <returns>配置节内容</returns>
    [HttpGet("enhanced/section/{section}")]
    public ActionResult GetConfigurationSection(string section)
    {
        try
        {
            _logger.LogInformation("Getting configuration section: {Section}", section);
            
            var result = (object?)(section.ToLowerInvariant() switch
            {
                "database" => _enhancedConfigFactory.GetDatabaseConfiguration(),
                "jwt" => _enhancedConfigFactory.GetJwtConfiguration(),
                "server" => _enhancedConfigFactory.GetServerConfiguration(),
                "cache" or "cachesettings" => _enhancedConfigFactory.GetCacheSettingsConfiguration(),
                "logging" => _enhancedConfigFactory.GetLoggingConfiguration(),
                "security" => _enhancedConfigFactory.GetSecurityConfiguration(),
                "upload" => _enhancedConfigFactory.GetUploadConfiguration(),
                "sms" => _enhancedConfigFactory.GetSmsConfiguration(),
                "cors" => _enhancedConfigFactory.GetCorsConfiguration(),
                "api" => _enhancedConfigFactory.GetApiConfiguration(),
                "ratelimit" => _enhancedConfigFactory.GetRateLimitConfiguration(),
                "lock" => _enhancedConfigFactory.GetLockConfiguration(),
                "permission" => _enhancedConfigFactory.GetPermissionConfiguration(),
                "extension" => _enhancedConfigFactory.GetExtensionConfiguration(),
                "mongodb" => _enhancedConfigFactory.GetMongoDbConfiguration(),
                "clickhouse" => _enhancedConfigFactory.GetClickHouseConfiguration(),
                _ => null
            });

            if (result == null)
            {
                return NotFound(new { error = $"Configuration section '{section}' not found or not supported" });
            }

            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get configuration section: {Section}", section);
            return BadRequest(new { error = ex.Message });
        }
    }

    #endregion
}
